<?php

/**
 * 命令行执行，Text协议服务端，异步处理任务。
 *
 * 调用方法：
 *
 * 1、 telnet 127.0.0.1 9021
 * 2、 stream_socket_client('tcp://127.0.0.1:9021', $errCode, $errMessage);
 * 3、 new AsyncTcpConnection('text://127.0.0.1:9021'); 将数据异步发送给这些任务进程，异步处理，异步得到处理结果。
 *
 * Text协议服务 可以内嵌到 WebSocket 服务的 onWorkerStart 回调方法内，用于接收消息，然后通过 WebSocket 下发给用户。
 *
 */

require './comm.php';

use Workerman\Worker;
use Workerman\Lib\Timer;

Worker::$logFile = ROOT_PATH.'runtime/log/text.log';
Worker::$pidFile = ROOT_PATH.'runtime/pid_text.log';

$textWorker = new Worker("text://0.0.0.0:9021");

$textWorker->count = 4;
$textWorker->reusePort = true;
$textWorker->name = 'textWorker';

$textWorker->onConnect = function($connection)
{
    $connId = $connection->id;
    $connection->lastTime = time();

    echo PHP_EOL. "客户端 #$connId 上线，IP：" . $connection->getRemoteIp() .PHP_EOL;

    $connection->send('{"action": "connect", "data": "' . $connId . '"}');
};

/**
 * 异步处理任务
 * @param $connection
 * @param $data
 */
$textWorker->onMessage = function($connection, $data)
{
    $connId = $connection->id;

    echo PHP_EOL. '服务端收到 #' .$connId. ' 的消息：' .PHP_EOL. $data .PHP_EOL;

    //todo...

    $connection->send('服务端收到 #' .$connId. ' 的消息：' . $data);
};

$textWorker->onError = function($connection, $code, $message)
{
    echo PHP_EOL. "error: [$code] $message" .PHP_EOL;
    $connection->errorCode = $code;
    $connection->close();
};

$textWorker->onClose = function($connection)
{
    echo PHP_EOL. '客户端 #' . $connection->id .' 断开'. PHP_EOL;

    if (isset($connection->timerId)) {
        Timer::del($connection->timerId);
    }
};

$textWorker->listen();

Worker::runAll();
